package com.zealfi.wk.netty.udp;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.socket.DatagramPacket;
import io.netty.handler.codec.MessageToMessageDecoder;
import io.netty.util.CharsetUtil;

import java.util.List;

/**
 * Created by kuan at 2018-06-14 下午 5:24
 */
public class LogEventDecoder extends MessageToMessageDecoder<DatagramPacket> {

    @Override
    protected void decode(ChannelHandlerContext ctx, DatagramPacket msg, List<Object> out) throws Exception {
        ByteBuf byteBuf = msg.content();
        int i = byteBuf.indexOf(0, byteBuf.readableBytes(), LogEvent.SEPARATOR);
        String fileName = byteBuf.slice(0, i).toString(CharsetUtil.UTF_8);
        String logMsg = byteBuf.slice(i + 1, byteBuf.readableBytes()).toString(CharsetUtil.UTF_8);
        out.add(new LogEvent(msg.sender(), fileName, logMsg, System.currentTimeMillis()));
    }
}
